package com.cdream.basic.java8.io.webserver.connector;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author cdream
 * @date 2022/8/25
 */
@Slf4j
public class Request {
    private static final int BUFFER_SIZE = 1024;
    private InputStream input;
    private String uri;

    public Request(InputStream input) {
        this.input = input;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }
    public void parse(){
        int length=0;
        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            length = input.read(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < length; j++) {
            sb.append((char) buffer[j]);
        }
        uri = parseUri(sb.toString());

    }

    private String parseUri(String request) {
        int index1,index2;
        index1 = request.indexOf(" ");
        if (index1!=-1){
            index2 = request.indexOf(" ",index1+1);
            if (index2>index1){
                return request.substring(index1+1,index2);
            }
        }
        return "";
    }

    public static void main(String[] args) {
       String request = "GET /index.html HTTP/1.1";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(request.getBytes());
        Request req = new Request(inputStream);
        req.parse();
        log.info(req.uri);
    }
}
